package cn.qingyun.gis.modules.scenes.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.qingyun.gis.modules.scenes.contant.ExcutorType;
import cn.qingyun.gis.modules.scenes.service.ISchemaService;
import cn.qingyun.gis.modules.scenes.util.DbSqlExecutor;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@DS("scenes_offensive")
public class ISchemaServiceImpl implements ISchemaService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void executeSqlScript(String sqlScript) {
        if (CharSequenceUtil.isNotBlank(sqlScript)) {
            this.executeSqlScript(ExcutorType.JDBCTEMPLATE, null, sqlScript);
        }
    }

    @Override
    public void executeSqlScript(String executor, String dataSourceName, String sqlScript) {
        if (CharSequenceUtil.isNotBlank(sqlScript)) {
            if (ExcutorType.JDBCTEMPLATE.equals(executor)) {
                jdbcTemplate.execute(sqlScript);
            } else {
                DbSqlExecutor.executePreparedStatement(dataSourceName, sqlScript);
            }
        }
    }

    @Override
    public void executeSqlScriptOfDb(String dbName, String sqlScript) {
        if (CharSequenceUtil.isNotBlank(sqlScript)) {
            DynamicDataSourceContextHolder.push(StrUtil.emptyToDefault(dbName, "scenes_offensive"));
            jdbcTemplate.execute(sqlScript);
            DynamicDataSourceContextHolder.clear();
        }
    }

    @Override
    public String bakTableAndData(String tableName) {
        String bakTableName = String.format("%s_%s", tableName, DatePattern.PURE_DATE_FORMAT.format(DateUtil.date()));
        this.executeSqlScript(String.format("CREATE TABLE IF NOT EXISTS %s AS SELECT * from %s", bakTableName, tableName));
        return bakTableName;
    }

    @Override
    public String bakTableAndData(String schema, String tableName) {
        String bakTableName = String.format("%s.%s_%s", schema, tableName, DatePattern.PURE_DATE_FORMAT.format(DateUtil.date()));
        this.executeSqlScript(String.format("CREATE TABLE IF NOT EXISTS %s AS SELECT * from %s.%s", bakTableName, schema, tableName));

        return bakTableName;
    }

    @Override
    public Long getTableCount(String sqlScript) {
        long rowCount = 0;
        if (CharSequenceUtil.isNotBlank(sqlScript)) {
            rowCount = jdbcTemplate.queryForObject(sqlScript, Long.class);
        }
        return rowCount;
    }
}
